<?php

/**
 *  签约查询接口
 *  out_trade_no  商户签约单号
 */




// 设置公共请求参数
$method = "heepay.agreement.bank.sign.query";
$version = "1.0";
$merch_id = "1664502";
$t=time();
$timestamp=date('Y-m-d H:i:s', $t);



// 设置自己的私钥
$private_key_str =
    "-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC5XkR5gTRgWLAUeyCvnQZA4pdZ6ayV8R+//KzQjDW18SEaFb/g+9b4jX6tyWniEXWYhXrHXyTbI6ZvykRpD2HfMo1Bvb1OKIVZYKG9chJmcekGKufbmQ4Pxuoy72I8Qhi8zmO29pROE7nM7EHgh1aYtcpJIBmq9Zuc8BddIk6t4Cxo6NMtHSbgzXCcqw67zCRDyf8mLZIc+o5ObzNZqbqAwD7bRUctCbYlUumXNJYBzbQ3aNQxZow1GDw23zbqqPgRVI3iXyNX5FWipTMUgGDpo6wDF3hOT1Z0xRdtBfEkdT6UyruRKGbbWiDd9roa75W4mlmvM0y7g7ZhuVkoaJn7AgMBAAECggEAFGeKBg3w5AIfL8H18R7Jx26p1l3gf4jRQ+Leav5kEyj9yc9HFc7i9O0uWpbnLtlZJnba8wNIHU8pTPjo2t+0mEsKPYhTRD01oIcAhsf9uoUjb2hdqVCJubbdpMmw+I0WCAJ3+3XdEVMeiq4e+kYrhBfOson0CVuLy5SqHbhfDMiF6SzRiTFMAELos7SwfjXZ0VAclGP7do/XWyUp2b2l9Z0nnaeKU2ecNBZlDXKcpsZ2Omz8HIXyJpeKooN63DSkjobPm6+/saNAL5118ZC8SxnvbZ61gsEk8/feHoYr58g6zgllLEb5uR7DJjmxrCF/bMqGv2OQ35s0cnPwUds/cQKBgQD7JACTjg2D/mvBSeZxsmOiLqJIoxeUOlH7OliPe6uF9XAJat2LJCpN5UPbUqgBC280SvzhJG103WeZIBNYiRqxC0qQUw1qUkpavJ1TkYw7lO5m/9b5TebQ05qTiBWd1DmJYbXfPQRjwjAG2/MkGIvdnZ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loiuhP54o8tP3z2ddCloWWzd+ZtuWG9AOd+vkZNkiDM4oex934oR/G7qbNBa5i6hIKZ3JJBVkGnuVA7tftVCRCsqCvgwpL6R/QIDAQAB
-----END PUBLIC KEY-----";

// 设置业务请求参数

$t=time();
$out_trade_time=date('Y-m-d H:i:s', $t);

$biz_content = array(
    //商户签约单号
    "out_trade_no" => "121212112",
);




// 将业务参数转换为JSON字符串
$biz_content_json = json_encode($biz_content,JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES);
//输出待加密参数
echo "待加密参数".$biz_content_json;
echo "<br/><hr>";




//组装签名串

class SignatureProcessor {
    private $postCharset = 'UTF-8'; // 设置你所需的字符集

    function checkEmpty($value) {
        return empty($value); // 检查值是否为空
    }

    function characet($data, $charset) {
        // 在这里实现你的字符编码转换逻辑
        return $data;
    }

    function echoDebug($message) {
        // 在这里实现你的调试逻辑
        // 例如：echo $message;
    }

    function getSignContent($params) {
        ksort($params); // 按键名对参数数组进行排序
        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                $v = $this->characet($v, $this->postCharset);
                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }
        $stringToBeSigned = str_replace('\/', '/', $stringToBeSigned);
        return $stringToBeSigned;
    }
}
// 签名参数组装
$params = array(
    'biz_content' => $biz_content_json,
    'merch_id' => $merch_id,
    'method' => 'heepay.agreement.bank.sign.query',
    'timestamp' => $timestamp,
    'version' => '1.0',
);
$signatureProcessor = new SignatureProcessor();
$signatureContent = $signatureProcessor->getSignContent($params);
echo "生成的签名明文数据: " . $signatureContent;
echo "<br/><hr>";







// 对签名字符串进行的RSA签名
$private_key = openssl_pkey_get_private($private_key_str);
openssl_sign($signatureContent, $signature, $private_key, OPENSSL_ALGO_SHA1);
$sign = base64_encode($signature);
//输出签名后数据
echo "签名后参数".$sign;
echo "<br/><hr>";




// 构建请求的JSON数据
$request_data = array(
    "method" => $method,
    "version" => $version,
    "merch_id" => $merch_id,
    "biz_content" => $biz_content_json,
    "timestamp" => $timestamp,
    "sign" => $sign
);





// 目标URL
$url = 'https://Pay.Heepay.com/API/PageSign/Index.aspx';


// 将要发送的数据转换为JSON格式
$jsonString = json_encode($request_data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
$arrayData1 = DeleteValue($jsonString);
//输出请求数据
echo "请求json".$arrayData1;
echo "<br/><hr>";


// 创建Header选项
$options = array(
    'http' => array(
        'header'  => "Content-type: application/json\r\n",
        'method'  => 'POST',
        'content' => $arrayData1,
    ),
);

// 创建上下文选项
$context  = stream_context_create($options);

// 发送POST请求并获取响应
$response = file_get_contents($url, false, $context);

if ($response === false) {
    // 处理请求失败的情况
    echo "Failed to send POST request.";
} else {
    // 处理请求成功的响应
    echo $response;
    echo "<br/><hr>";
}

$responsed = json_decode($response,true);






function DeleteValue($jsonString)
{

    // 将 JSON 字符串解码为关联数组
    $arrayData = json_decode($jsonString, true);

// 处理 biz_content 键的值，去掉外层双引号
    if (isset($arrayData['biz_content'])) {
        $arrayData['biz_content'] = json_decode($arrayData['biz_content'], true);
    }

// 打印结果
    $arrayData1 = json_encode($arrayData,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);

    return $arrayData1;

}
// 获取解析后的参数

$data1 = $responsed['data'];

//解密返回的data

/* 分段解密方法
对加密数据进行处理（例如Base64解码）
 */
$encryptedData = base64_decode($data1);

// 定义每个分段的大小
$chunkSize = 256; // 2048-bit key can decrypt 256 bytes

$PRIVATEkey=$private_key_str;


// 分段解密
$decryptedData = '';
for ($i = 0; $i < strlen($encryptedData); $i += $chunkSize) {
    $chunk = substr($encryptedData, $i, $chunkSize);
    openssl_private_decrypt($chunk, $decryptedChunk, $PRIVATEkey);
    $decryptedData .= $decryptedChunk;
}
// 输出接口返回解密后数据
echo "接口返回解密后数据".$decryptedData;
echo "<br/><hr>";





?>
